#ifndef RING_H
#define RING_H

#include <stdint.h>
#include <string.h>
#include <malloc.h>

struct ring_queue {
    int16_t head;
    int16_t tail;
    int16_t length;
    int16_t count;
    void **ele;
};

struct ring_queue *rq_alloc( uint32_t size) {
    struct ring_queue *rq =  (struct ring_queue *)malloc(sizeof(struct ring_queue));
    rq->head = rq->tail = 0;
    rq->length = size;
    rq->count = 0;
    rq->ele = (void**)calloc(size , sizeof(void*));
    return rq;
}

void rq_free(struct ring_queue * rq) {
    free(rq->ele);
    free(rq);
}

int rq_count(struct ring_queue * rq) {
    return rq->count;
}

bool rq_enqueue(struct ring_queue * rq , void *elem ) {
    int16_t t = ( rq->tail + 1 ) % rq->length ;
    if( t == rq->head ) {
        return false;
    }
    rq->ele[rq->tail] = elem ;
    rq->tail = t;
    rq->count++;
    return true;
}

void* rq_dequeue(struct ring_queue * rq ) {
    if( rq->head == rq->tail) {
        return NULL;
    }
    void *e = rq->ele[rq->head];
    rq->head = ( rq->head + 1 ) % rq->length;
    rq->count--;
    return e;
}


#endif